import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart';
import 'package:sqflite/sqflite.dart';

/// 文件服务类，统一处理应用中的文件操作
class FileServe {
  static final FileServe _instance = FileServe._internal();
  late String _appDataDir;
  bool _initialized = false;

  factory FileServe() {
    return _instance;
  }

  FileServe._internal();

  /// 初始化文件服务
  Future<void> initialize() async {
    if (_initialized) return;
    
    try {
      print('FileServe: 开始初始化文件服务');
      
      // 尝试获取Android/data目录作为存储路径
      if (Platform.isAndroid) {
        print('FileServe: Android平台，尝试获取Android/data目录');
        
        try {
          // 使用path_provider获取外部存储目录
          Directory? externalDir = await getExternalStorageDirectory();
          if (externalDir != null) {
            print('FileServe: 获取到外部存储目录: ${externalDir.path}');
            
            // 通常路径是 /storage/emulated/0/Android/data/your_package_name/files
            // 获取 Android/data 目录的路径
            String androidDataPath = externalDir.path;
            // 从路径中移除包名和files部分
            final appDirIndex = androidDataPath.indexOf('/Android/data/');
            if (appDirIndex != -1) {
              // /storage/emulated/0/Android/data/
              String dataBasePath = androidDataPath.substring(0, appDirIndex + 14);
              print('FileServe: Android/data 基础路径: $dataBasePath');
              
              // 创建应用专属目录
              final appDir = Directory(path.join(dataBasePath, 'com.example.patchouli_knowledge'));
              if (!await appDir.exists()) {
                print('FileServe: 创建应用专用目录: ${appDir.path}');
                await appDir.create(recursive: true);
              }
              
              _appDataDir = appDir.path;
              print('FileServe: 应用数据目录设置为: $_appDataDir');
            } else {
              print('FileServe: 无法从路径中识别Android/data目录，回退到其他方式');
              await _fallbackToDocumentsDirectory();
            }
          } else {
            print('FileServe: 无法获取外部存储目录，回退到其他方式');
            await _fallbackToDocumentsDirectory();
          }
        } catch (e) {
          print('FileServe: 获取Android/data目录失败: $e');
          print('FileServe: 回退到其他方式');
          await _fallbackToDocumentsDirectory();
        }
      } else {
        // 非Android平台使用应用文档目录
        await _fallbackToDocumentsDirectory();
      }
      
      // 测试写入权限
      try {
        final testFile = File(path.join(_appDataDir, '_permission_test.txt'));
        await testFile.writeAsString('测试写入 - ${DateTime.now()}');
        print('FileServe: 写入测试成功');
        
        final content = await testFile.readAsString();
        print('FileServe: 读取测试成功: $content');
        
        await testFile.delete();
        print('FileServe: 删除测试文件成功');
      } catch (e) {
        print('FileServe: 存储权限测试失败: $e');
        print('FileServe: 应用可能无法正常工作，请确保授予了存储权限');
      }
      
      // 创建必要的子目录
      print('FileServe: 创建子目录');
      await _createSubDirectories();
      
      // 创建默认的知拾食用指南.md文件
      await _ensureUserGuideExists();

      // 初始化记忆数据库
      await _initializeMemoryDatabase();
      
      _initialized = true;
      print('FileServe: 初始化完成，应用数据目录: $_appDataDir');
    } catch (e) {
      print('FileServe: 初始化文件服务失败: $e');
      print('FileServe: 堆栈: ${StackTrace.current}');
      rethrow;
    }
  }
  
  /// 回退到使用应用文档目录
  Future<void> _fallbackToDocumentsDirectory() async {
    print('FileServe: 使用应用文档目录作为备选');
    Directory? appDir;
    
    try {
      appDir = await getApplicationDocumentsDirectory();
      print('FileServe: 获取到应用文档目录: ${appDir.path}');
    } catch (e) {
      print('FileServe: 获取应用文档目录失败: $e');
      print('FileServe: 尝试使用临时目录');
      appDir = await getTemporaryDirectory();
      print('FileServe: 使用临时目录: ${appDir.path}');
    }
    
    _appDataDir = path.join(appDir.path, 'patchouli_knowledge');
    print('FileServe: 应用数据目录设置为: $_appDataDir');
    
    // 确保基础目录存在
    final baseDir = Directory(_appDataDir);
    if (!await baseDir.exists()) {
      print('FileServe: 创建基础目录: $_appDataDir');
      await baseDir.create(recursive: true);
      print('FileServe: 基础目录创建成功');
    } else {
      print('FileServe: 基础目录已存在');
    }
  }

  /// 初始化方法的别名，兼容main.dart中的调用
  Future<void> init() async {
    return await initialize();
  }

  /// 创建必要的子目录
  Future<void> _createSubDirectories() async {
    final directories = [
      'docs',      // 存储文档
      'doc',       // 实际文档存储（与docs保持一致性）
      'chat',      // 存储聊天记录
      'config',    // 存储配置信息
      'temp',      // 临时文件目录
      'cache',     // 缓存目录
    ];
    
    for (final dir in directories) {
      final directory = Directory(path.join(_appDataDir, dir));
      print('创建目录: ${directory.path}');
      if (!await directory.exists()) {
        await directory.create(recursive: true);
        print('目录创建成功: ${directory.path}');
      } else {
        print('目录已存在: ${directory.path}');
      }
    }
  }

  /// 获取Android/obb目录路径
  Future<String?> getAndroidObbPath() async {
    if (!Platform.isAndroid) return null;
    
    try {
      Directory? externalDir = await getExternalStorageDirectory();
      if (externalDir != null) {
        // 通常路径是 /storage/emulated/0/Android/data/your_package_name/files
        String androidDataPath = externalDir.path;
        final appDirIndex = androidDataPath.indexOf('/Android/data/');
      }
    } catch (e) {
      print('FileServe: 获取Android/obb目录失败: $e');
    }
    return null;
  }

  /// 确保知拾食用指南.md文件存在
  Future<void> _ensureUserGuideExists() async {
    try {
      final docDir = Directory(path.join(_appDataDir, 'doc'));
      final aboutFile = File(path.join(docDir.path, '知拾食用指南.md'));
      
      if (!await aboutFile.exists()) {
        print('FileServe: 知拾食用指南.md文件不存在，创建默认文件');
        const defaultContent = '''
# 知拾使用指南

## 欢迎使用知拾!

这是您的个人知识库！你可以通过主页的加号来上传你的知识文档
除了支持docx，txt，md和pdf文档的上传
我们还支持使用图片上传你的文档！

看到一篇有用的知识，只需要截图或者拿起你的手机拍个照就可以自动地转化为你知识库里面的文档，不需要你过多地操作！
我们使用ocr技术和大模型来帮你整理图片里面的知识。

在主页上方的搜索框可以主动搜索你知识库里面的信息，也可以点击中间的知拾的logo和大模型聊天，大模型会主动的查询你的知识库来回答你的问题。

自定义你的身份，我们的大模型会根据你的身份给出合理的建议


## 主要功能

### 知识管理
- **文档上传**：支持多种格式的文档上传，包括PDF、TXT、DOCX、图片格式等。
- **自动分类**：系统会自动分析文档内容并进行分类整理。
- **知识卡片**：直观地展示您的知识库结构，方便快速查找。

### 智能问答
- **自然语言交互**：您可以用日常语言向系统提问。
- **知识库检索**：系统会自动从您的文档中找到最相关的信息。
- **智能推荐**：根据您的兴趣和使用习惯，提供个性化的知识推荐。

### 用户体验
- **个性化设置**：自定义您的身份标签和昵称。
- **聊天记录**：保存您与系统的对话历史，方便回顾。
- **多端同步**：计划支持多设备访问和同步（敬请期待）。

## 使用说明

1. **添加文档**：点击主页右下角的"+"按钮上传新文档。
2. **浏览知识库**：在主页底部的知识卡片中浏览您的文档。
3. **提问**：点击中央的图标开始与Tina对话。

''';
        await aboutFile.writeAsString(defaultContent);
        print('FileServe: 知拾食用指南.md文件创建成功');
      } else {
        print('FileServe: 知拾食用指南.md文件已存在');
      }
    } catch (e) {
      print('FileServe: 创建知拾食用指南.md文件失败: $e');
    }
  }

  /// 初始化记忆数据库
  Future<void> _initializeMemoryDatabase() async {
    try {
      final chatDir = Directory(path.join(_appDataDir, 'chat'));
      if (!await chatDir.exists()) {
        await chatDir.create(recursive: true);
      }
      
      final memoryDbPath = path.join(chatDir.path, 'memory.tina');
      print('FileServe: 初始化记忆数据库: $memoryDbPath');
      
      // 使用sqflite打开数据库，如果不存在会自动创建
      final db = await openDatabase(
        memoryDbPath,
        version: 1,
        onCreate: (Database db, int version) async {
          print('FileServe: 创建记忆数据库表结构');
          await db.execute('''
            CREATE TABLE logs (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              time TEXT NOT NULL,
              content TEXT NOT NULL
            )
          ''');
          print('FileServe: 记忆数据库表创建成功');
        },
      );
      
      // 关闭数据库连接
      await db.close();
      print('FileServe: 记忆数据库初始化完成');
    } catch (e) {
      print('FileServe: 初始化记忆数据库失败: $e');
      print('FileServe: 堆栈: ${StackTrace.current}');
    }
  }

  /// 获取记忆数据库路径
  String getMemoryDatabasePath() {
    return path.join(_appDataDir, 'chat', 'memory.tina');
  }

  /// 获取应用数据目录
  String get appDataDir => _appDataDir;

  /// 保存用户信息
  Future<bool> saveUserInfo(Map<String, dynamic> userInfo) async {
    try {
      if (!_initialized) await initialize();
      
      final userFile = File(path.join(_appDataDir, 'config', 'user_info.json'));
      await userFile.writeAsString(jsonEncode(userInfo));
      return true;
    } catch (e) {
      print('保存用户信息失败: $e');
      return false;
    }
  }

  /// 读取用户信息
  Future<Map<String, dynamic>?> readUserInfo() async {
    try {
      if (!_initialized) await initialize();
      
      final userFile = File(path.join(_appDataDir, 'config', 'user_info.json'));
      if (await userFile.exists()) {
        final content = await userFile.readAsString();
        return jsonDecode(content) as Map<String, dynamic>;
      }
      return null;
    } catch (e) {
      print('读取用户信息失败: $e');
      return null;
    }
  }

  /// 保存聊天历史
  Future<bool> saveChatHistory(Map<String, dynamic> chatData, {String? date}) async {
    try {
      if (!_initialized) await initialize();
      
      final today = date ?? DateFormat('yyyy-MM-dd').format(DateTime.now());
      final chatFile = File(path.join(_appDataDir, 'chat', '$today.json'));
      
      await chatFile.writeAsString(jsonEncode(chatData));
      return true;
    } catch (e) {
      print('保存聊天历史失败: $e');
      return false;
    }
  }

  /// 读取聊天历史
  Future<Map<String, dynamic>?> readChatHistory({String? date}) async {
    try {
      if (!_initialized) await initialize();
      
      final chatDate = date ?? DateFormat('yyyy-MM-dd').format(DateTime.now());
      final chatFile = File(path.join(_appDataDir, 'chat', '$chatDate.json'));
      
      if (await chatFile.exists()) {
        final content = await chatFile.readAsString();
        return jsonDecode(content) as Map<String, dynamic>;
      }
      return null;
    } catch (e) {
      print('读取聊天历史失败: $e');
      return null;
    }
  }

  /// 获取指定文档的路径
  Future<String?> getDocumentPath(String documentId) async {
    try {
      if (!_initialized) await initialize();
      
      // 根据文档ID获取文档路径
      // 实际实现可能需要查询数据库或配置文件
      final docIndexFile = File(path.join(_appDataDir, 'docs', 'index.json'));
      if (await docIndexFile.exists()) {
        final content = await docIndexFile.readAsString();
        final Map<String, dynamic> index = jsonDecode(content);
        
        if (index.containsKey(documentId)) {
          return index[documentId] as String;
        }
      }
      return null;
    } catch (e) {
      print('获取文档路径失败: $e');
      return null;
    }
  }

  /// 存储文档索引
  Future<bool> saveDocumentIndex(Map<String, String> docIndex) async {
    try {
      if (!_initialized) await initialize();
      
      final indexFile = File(path.join(_appDataDir, 'docs', 'index.json'));
      await indexFile.writeAsString(jsonEncode(docIndex));
      return true;
    } catch (e) {
      print('保存文档索引失败: $e');
      return false;
    }
  }

  /// 保存应用配置
  Future<bool> saveAppConfig(Map<String, dynamic> config) async {
    try {
      if (!_initialized) await initialize();
      
      final configFile = File(path.join(_appDataDir, 'config', 'app_config.json'));
      await configFile.writeAsString(jsonEncode(config));
      return true;
    } catch (e) {
      print('保存应用配置失败: $e');
      return false;
    }
  }

  /// 读取应用配置
  Future<Map<String, dynamic>?> readAppConfig() async {
    try {
      if (!_initialized) await initialize();
      
      final configFile = File(path.join(_appDataDir, 'config', 'app_config.json'));
      if (await configFile.exists()) {
        final content = await configFile.readAsString();
        return jsonDecode(content) as Map<String, dynamic>;
      }
      return null;
    } catch (e) {
      print('读取应用配置失败: $e');
      return null;
    }
  }

  /// 临时文件存储
  Future<String> saveTempFile(String content, {String? filename}) async {
    try {
      if (!_initialized) await initialize();
      
      final tempFileName = filename ?? '${DateTime.now().millisecondsSinceEpoch}.txt';
      final tempFile = File(path.join(_appDataDir, 'temp', tempFileName));
      
      await tempFile.writeAsString(content);
      return tempFile.path;
    } catch (e) {
      print('保存临时文件失败: $e');
      rethrow;
    }
  }

  /// 清理临时文件
  Future<void> cleanTempFiles() async {
    try {
      if (!_initialized) await initialize();
      
      final tempDir = Directory(path.join(_appDataDir, 'temp'));
      if (await tempDir.exists()) {
        // 删除文件夹内容但保留文件夹
        await for (final entity in tempDir.list()) {
          await entity.delete(recursive: true);
        }
      }
    } catch (e) {
      print('清理临时文件失败: $e');
    }
  }

  /// 获取指定类型的配置
  Future<Map<String, dynamic>> getConfig(String configType) async {
    try {
      if (!_initialized) await initialize();
      
      String fileName;
      Map<String, dynamic> defaultConfig;
      print('获取配置: $configType');
      
      if (configType.toLowerCase() == 'llm') {
        fileName = 'LLM.json';
        // LLM配置的默认值
        defaultConfig = {
          'model': 'qwen-plus',
          'api_key': 'sk-aa328698ca6f4a7c9c0dde0b9851a772',
          'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
        };
      } else if (configType.toLowerCase() == 'vivo_ocr') {
        fileName = 'vivo_ocr.json';
        print('准备获取OCR配置');
        // VIVO OCR配置的默认值
        defaultConfig = {
          'app_id': '2025223721',
          'secret_key': 'coirgJhVbJPuXCPj',
          'api_url': 'http://api-ai.vivo.com.cn/ocr/general_recognition'
        };
        print('OCR默认配置准备完成: $defaultConfig');
      } else {
        fileName = '${configType.toLowerCase()}_dataset.json';
        // Dify数据集配置的默认值
        defaultConfig = {
          "dify_dataset_api": "dataset-0ZHdF2a9wBBiCrbMUDv8oDjp",
          "dataset_name": "",
          "dify_base_url": "http://132.232.203.3/v1",
          "indexing_technique": "high_quality",
          "embedding_model": "text-embedding-v1",
          "embedding_model_provider": "tongyi",
          "retrieval_model": {
            "search_method": "hybrid_search",
            "reranking_enable": true,
            "reranking_model": {
              "reranking_provider_name": "tongyi",
              "reranking_model_name": "gte-rerank"
            },
            "top_k": 10,
            "score_threshold_enabled": false
          },
          "other_config": {
            "process_rule": {
              "rules": {
                "pre_processing_rules": [
                  {
                    "id": "remove_extra_spaces",
                    "enabled": true
                  },
                  {
                    "id": "remove_urls_emails",
                    "enabled": true
                  }
                ],
                "segmentation": {
                  "separator": "###",
                  "max_tokens": 500
                }
              },
              "mode": "custom"
            }
          },
          "dataset_id": ""
        };
      }
      
      final configFile = File(path.join(_appDataDir, 'config', fileName));
      print('尝试读取配置文件: ${configFile.path}');
      
      if (await configFile.exists()) {
        // 如果配置文件存在，则读取内容
        final content = await configFile.readAsString();
        print('读取到内容: $content');
        final config = jsonDecode(content);
        
        if (configType.toLowerCase() == 'vivo_ocr') {
          print('已加载OCR配置: $config');
        }
        
        return config;
      } else {
        // 如果配置文件不存在，创建默认配置并保存
        print('配置文件不存在，创建默认配置: ${configFile.path}');
        final configDir = Directory(path.join(_appDataDir, 'config'));
        if (!await configDir.exists()) {
          print('配置目录不存在，创建中...');
          await configDir.create(recursive: true);
        }
        
        await configFile.writeAsString(jsonEncode(defaultConfig));
        print('创建默认配置文件成功');
        
        if (configType.toLowerCase() == 'vivo_ocr') {
          print('已创建默认OCR配置: $defaultConfig');
        }
        
        return defaultConfig;
      }
    } catch (e) {
      print('获取${configType}配置失败: $e');
      print('堆栈: ${StackTrace.current}');
      // 返回一个空配置，避免程序崩溃
      return {};
    }
  }

  /// 返回配置文件路径
  String returnConfigPath() {
    return path.join(_appDataDir, 'config');
  }

  /// 获取文档ID映射
  Future<Map<String, dynamic>> getDocIdMappings() async {
    try {
      if (!_initialized) await initialize();
      
      final docIdMappingFile = File(path.join(_appDataDir, 'docs', 'doc_id_mappings.json'));
      if (await docIdMappingFile.exists()) {
        final content = await docIdMappingFile.readAsString();
        return jsonDecode(content);
      } else {
        // 如果文件不存在，创建一个空映射并保存
        final emptyMapping = <String, dynamic>{};
        await docIdMappingFile.writeAsString(jsonEncode(emptyMapping));
        return emptyMapping;
      }
    } catch (e) {
      print('获取文档ID映射失败: $e');
      return <String, dynamic>{};
    }
  }

  /// 更新文档ID映射
  Future<bool> updateDocIdMapping(String docId, String filePath) async {
    try {
      if (!_initialized) await initialize();
      
      final docIdMappingFile = File(path.join(_appDataDir, 'docs', 'doc_id_mappings.json'));
      Map<String, dynamic> mappings;
      
      if (await docIdMappingFile.exists()) {
        final content = await docIdMappingFile.readAsString();
        mappings = jsonDecode(content);
      } else {
        mappings = {};
      }
      
      mappings[docId] = filePath;
      await docIdMappingFile.writeAsString(jsonEncode(mappings));
      return true;
    } catch (e) {
      print('更新文档ID映射失败: $e');
      return false;
    }
  }

  /// 更改Dify数据集配置
  Future<bool> changeDifyDatasetConfig(Map<String, dynamic> newConfig) async {
    try {
      if (!_initialized) await initialize();
      
      final configFile = File(path.join(_appDataDir, 'config', 'dify_dataset.json'));
      await configFile.writeAsString(jsonEncode(newConfig));
      return true;
    } catch (e) {
      print('更改Dify数据集配置失败: $e');
      return false;
    }
  }

  /// 根据文档ID获取文件路径
  Future<String?> getFilePathByDocId(String docId) async {
    try {
      if (!_initialized) await initialize();
      
      final mappings = await getDocIdMappings();
      return mappings.containsKey(docId) ? mappings[docId] as String : null;
    } catch (e) {
      print('根据文档ID获取文件路径失败: $e');
      return null;
    }
  }

  /// 移除文档ID映射
  Future<bool> removeDocIdMapping(String docId) async {
    try {
      if (!_initialized) await initialize();
      
      final docIdMappingFile = File(path.join(_appDataDir, 'docs', 'doc_id_mappings.json'));
      if (await docIdMappingFile.exists()) {
        final content = await docIdMappingFile.readAsString();
        final Map<String, dynamic> mappings = jsonDecode(content);
        
        if (mappings.containsKey(docId)) {
          mappings.remove(docId);
          await docIdMappingFile.writeAsString(jsonEncode(mappings));
          return true;
        }
      }
      return false;
    } catch (e) {
      print('移除文档ID映射失败: $e');
      return false;
    }
  }

  /// 获取用户信息的别名方法，与readUserInfo保持一致
  Future<Map<String, dynamic>?> getUserInfo() async {
    return await readUserInfo();
  }

  /// 获取知识卡片信息
  Future<List<Map<String, dynamic>>> getKnowledgeCardInfo() async {
    try {
      print('FileServe: 开始获取知识卡片信息');
      if (!_initialized) {
        print('FileServe: 尚未初始化，进行初始化');
        await initialize();
      }
      
      final List<Map<String, dynamic>> cardInfoList = [];
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      print('FileServe: 缓存目录路径: ${cacheDir.path}');
      
      if (await cacheDir.exists()) {
        print('FileServe: 缓存目录存在，开始扫描文件');
        await for (final entity in cacheDir.list()) {
          print('FileServe: 扫描到文件: ${entity.path}');
          if (entity is File && entity.path.endsWith('.json')) {
            final fileName = path.basename(entity.path);
            
            // 跳过标签统计文件（_tags.json）、全局标签文件（tag.json）和阅读位置文件（reading_positions.json）
            if (fileName.endsWith('_tags.json') || fileName == 'tag.json' || fileName == 'reading_positions.json') {
              print('FileServe: 跳过系统文件: ${entity.path}');
              continue;
            }
            
            try {
              print('FileServe: 尝试读取分类文档JSON文件: ${entity.path}');
              final content = await entity.readAsString();
              print('FileServe: 文件读取成功，内容长度: ${content.length}');
              final documents = jsonDecode(content) as List<dynamic>;
              print('FileServe: JSON解析成功，包含${documents.length}个文档');
              
              if (documents.isNotEmpty) {
                final categoryName = path.basenameWithoutExtension(entity.path);
                print('FileServe: 添加类别: $categoryName，文档数量: ${documents.length}');
                cardInfoList.add({
                  'category': categoryName,
                  'documents': documents,
                });
              } else {
                print('FileServe: 忽略空文档列表: ${entity.path}');
              }
            } catch (e) {
              print('FileServe: 读取知识卡片JSON文件失败: ${entity.path}, 错误: $e');
            }
          }
        }
      } else {
        print('FileServe: 缓存目录不存在: ${cacheDir.path}');
      }
      
      print('FileServe: 获取知识卡片完成，共${cardInfoList.length}个类别');
      return cardInfoList;
    } catch (e) {
      print('FileServe: 获取知识卡片信息失败: $e');
      print('FileServe: 堆栈: ${StackTrace.current}');
      return [];
    }
  }

  /// 添加文档到知识库
  Future<bool> addDocument(String filePath, String category) async {
    try {
      if (!_initialized) await initialize();
      
      // 确保文档目录存在
      final docDir = Directory(path.join(_appDataDir, 'doc'));
      if (!await docDir.exists()) {
        await docDir.create(recursive: true);
      }
      
      // 确保缓存目录存在
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        await cacheDir.create(recursive: true);
      }
      
      // 检查源文件是否存在
      final sourceFile = File(filePath);
      if (!await sourceFile.exists()) {
        print('FileServe: 源文件不存在: $filePath');
        return false;
      }
      
      // 获取文件名
      final fileName = path.basename(filePath);
      final destFile = File(path.join(docDir.path, fileName));
      
      // 如果文件不在doc目录中，则复制到doc目录
      if (path.dirname(filePath) != docDir.path) {
        await sourceFile.copy(destFile.path);
        print('FileServe: 文件已复制到文档目录: ${destFile.path}');
      } else {
        print('FileServe: 文件已在文档目录中: $filePath');
      }
      
      // 更新或创建类别的JSON文件
      final categoryFile = File(path.join(cacheDir.path, '$category.json'));
      List<Map<String, dynamic>> documents = [];
      
      if (await categoryFile.exists()) {
        final content = await categoryFile.readAsString();
        documents = List<Map<String, dynamic>>.from(
          jsonDecode(content).map((doc) => Map<String, dynamic>.from(doc))
        );
      }
      
      // 生成一个临时ID，格式为temp_加时间戳，这将在文档上传到Dify后被替换
      final tempId = 'temp_${DateTime.now().millisecondsSinceEpoch}';
      
      // 添加新文档信息
      final newDoc = {
        'title': path.basenameWithoutExtension(fileName), // 使用不含扩展名的文件名作为标题
        'path': destFile.path,
        'doc_id': tempId, // 使用临时ID
        'time': DateTime.now().toIso8601String()
      };
      
      // 检查文档是否已存在（基于路径）
      final existingIndex = documents.indexWhere((doc) => doc['path'] == destFile.path);
      if (existingIndex != -1) {
        documents[existingIndex] = newDoc;
        print('FileServe: 更新已存在的文档记录: ${newDoc['title']}');
      } else {
        documents.add(newDoc);
        print('FileServe: 添加新文档记录: ${newDoc['title']}');
      }
      
      // 保存更新后的文档列表
      await categoryFile.writeAsString(jsonEncode(documents));
      print('FileServe: 分类文件已更新: $category.json');
      
      return true;
    } catch (e) {
      print('FileServe: 添加文档失败: $e');
      print('FileServe: 堆栈: ${StackTrace.current}');
      return false;
    }
  }

  // 文件重命名
  Future<(List<Map<String, dynamic>>, int)?> renameFile(String category, String newname, String filePath) async {
    final currentFile = File(filePath);
    String fileExtension = path.extension(filePath);
    String directory = path.dirname(filePath);
    String newPath = path.join(directory, newname + fileExtension);
    await currentFile.rename(newPath);
    final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        await cacheDir.create(recursive: true);
      }
    final categoryFile = File(path.join(cacheDir.path, '$category.json'));
    List<Map<String, dynamic>> documents = [];
    if (await categoryFile.exists()) {
      final content = await categoryFile.readAsString();
      documents = List<Map<String, dynamic>>.from(
        jsonDecode(content).map((doc) => Map<String, dynamic>.from(doc))
      );
    }
    final existingIndex = documents.indexWhere((doc) => doc['path'] == filePath);
      if (existingIndex != -1) {
        documents[existingIndex]['title'] = newname + fileExtension;
        documents[existingIndex]['path'] = newPath;
        await categoryFile.writeAsString(jsonEncode(documents));
      }
    return (documents, existingIndex);
  }

  /// 获取所有分类标签
  Future<List<String>> getCategories() async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        print('FileServe: 缓存目录不存在，创建中...');
        await cacheDir.create(recursive: true);
        
        // 确保至少有一个默认分类
        final defaultCategories = ['软件说明', '计算机', '人工智能', '社会科学'];
        return defaultCategories;
      }
      
      // 获取所有JSON文件（每个文件代表一个分类）
      final List<FileSystemEntity> files = await cacheDir.list().toList();
      final List<String> categories = [];
      
      for (var file in files) {
        if (file is File && file.path.toLowerCase().endsWith('.json')) {
          // 从文件名中提取分类名称（移除.json扩展名）
          final fileName = path.basename(file.path);
          
          // 跳过标签统计文件（_tags.json）、全局标签文件（tag.json）和阅读位置文件（reading_positions.json）
          if (fileName.endsWith('_tags.json') || fileName == 'tag.json' || fileName == 'reading_positions.json') {
            continue;
          }
          
          final categoryName = fileName.substring(0, fileName.length - 5); // 移除'.json'
          categories.add(categoryName);
        }
      }
      
      // 如果没有找到分类，返回默认分类
      if (categories.isEmpty) {
        final defaultCategories = ['软件说明', '计算机', '人工智能', '社会科学'];
        return defaultCategories;
      }
      
      // 排序并返回分类
      categories.sort();
      return categories;
    } catch (e) {
      print('FileServe: 获取分类失败: $e');
      print('FileServe: 堆栈: ${StackTrace.current}');
      
      // 出错时返回默认分类
      return ['软件说明', '计算机', '人工智能', '社会科学'];
    }
  }
  
  /// 添加新分类
  Future<bool> addCategory(String categoryName) async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        await cacheDir.create(recursive: true);
      }
      
      // 创建空的分类文件
      final categoryFile = File(path.join(cacheDir.path, '$categoryName.json'));
      if (!await categoryFile.exists()) {
        await categoryFile.writeAsString(jsonEncode([]));
        print('FileServe: 创建新分类: $categoryName');
        return true;
      }
      
      // 分类已存在
      return true;
    } catch (e) {
      print('FileServe: 添加分类失败: $e');
      print('FileServe: 堆栈: ${StackTrace.current}');
      return false;
    }
  }

  /// 列出所有聊天历史文件
  Future<List<String>> listChatHistoryFiles() async {
    try {
      if (!_initialized) await initialize();
      
      final chatDir = Directory(path.join(_appDataDir, 'chat'));
      if (!await chatDir.exists()) {
        return [];
      }
      
      final files = await chatDir
          .list()
          .where((entity) => entity is File && entity.path.endsWith('.json'))
          .map((entity) => entity.path)
          .toList();
      
      // 按日期降序排序（最新的在前面）
      files.sort((a, b) => b.compareTo(a));
      
      return files;
    } catch (e) {
      print('列出聊天历史文件失败: $e');
      return [];
    }
  }

  /// 更新OCR配置
  Future<bool> updateOCRConfig(Map<String, dynamic> config) async {
    try {
      if (!_initialized) await initialize();
      
      // 确保配置目录存在
      final configDir = Directory(path.join(_appDataDir, 'config'));
      if (!await configDir.exists()) {
        await configDir.create(recursive: true);
      }
      
      // 写入OCR配置文件
      final ocrConfigFile = File(path.join(configDir.path, 'vivo_ocr.json'));
      await ocrConfigFile.writeAsString(jsonEncode(config));
      
      print('FileServe: OCR配置已更新');
      return true;
    } catch (e) {
      print('FileServe: 更新OCR配置失败: $e');
      return false;
    }
  }
  
  /// 更新文档ID
  Future<bool> updateDocumentId(String filePath, String tempId, String realId) async {
    try {
      if (!_initialized) await initialize();
      
      print('FileServe: 更新文档ID: $filePath, 从 $tempId 到 $realId');
      
      // 遍历所有分类文件，查找并更新文档ID
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        print('FileServe: 缓存目录不存在，无法更新文档ID');
        return false;
      }
      
      // 获取所有JSON文件（每个文件代表一个分类）
      final List<FileSystemEntity> files = await cacheDir.list().toList();
      bool updated = false;
      
      for (var entity in files) {
        if (entity is File && entity.path.toLowerCase().endsWith('.json')) {
          try {
            final fileName = path.basename(entity.path);
            
            // 跳过标签文件，它们的结构不同
            if (fileName.endsWith('_tags.json') || fileName == 'tag.json') {
              continue;
            }
            
            final content = await entity.readAsString();
            final jsonData = jsonDecode(content);
            
            // 确保是文档列表格式
            if (jsonData is! List) {
              continue;
            }
            
            List<Map<String, dynamic>> documents = List<Map<String, dynamic>>.from(
              jsonData.map((doc) => Map<String, dynamic>.from(doc))
            );
            
            // 查找匹配的文档
            bool categoryUpdated = false;
            for (int i = 0; i < documents.length; i++) {
              if (documents[i]['path'] == filePath || documents[i]['doc_id'] == tempId) {
                documents[i]['doc_id'] = realId;
                categoryUpdated = true;
                updated = true;
                print('FileServe: 在分类 ${path.basenameWithoutExtension(entity.path)} 中更新了文档ID');
              }
            }
            
            // 如果找到并更新了文档，保存更改
            if (categoryUpdated) {
              await entity.writeAsString(jsonEncode(documents));
            }
          } catch (e) {
            print('FileServe: 处理分类文件 ${entity.path} 失败: $e');
          }
        }
      }
      
      // 同时更新文档ID映射
      if (updated) {
        await updateDocIdMapping(realId, filePath);
        print('FileServe: 文档ID映射已更新');
      } else {
        print('FileServe: 未找到需要更新ID的文档');
      }
      
      return updated;
    } catch (e) {
      print('FileServe: 更新文档ID失败: $e');
      return false;
    }
  }
  
  /// 保存图片到临时目录
  Future<String> saveTempImage(List<int> imageBytes, String extension) async {
    try {
      if (!_initialized) await initialize();
      
      final tempFileName = '${DateTime.now().millisecondsSinceEpoch}.$extension';
      final tempFile = File(path.join(_appDataDir, 'temp', tempFileName));
      
      await tempFile.writeAsBytes(imageBytes);
      return tempFile.path;
    } catch (e) {
      print('保存临时图片失败: $e');
      rethrow;
    }
  }
  
  /// 从所有分类中删除文档
  Future<bool> removeDocumentFromCategories(String docId) async {
    try {
      if (!_initialized) await initialize();
      
      print('FileServe: 从所有分类中删除文档: $docId');
      
      // 遍历缓存目录下的所有分类文件
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        print('FileServe: 缓存目录不存在');
        return false;
      }
      
      bool documentRemoved = false;
      
      await for (final entity in cacheDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          try {
            final fileName = path.basename(entity.path);
            
            // 跳过标签文件，它们的结构不同
            if (fileName.endsWith('_tags.json') || fileName == 'tag.json') {
              continue;
            }
            
            // 读取分类文件
            final content = await entity.readAsString();
            final jsonData = jsonDecode(content);
            
            // 确保是文档列表格式
            if (jsonData is! List) {
              continue;
            }
            
            List<Map<String, dynamic>> documents = List<Map<String, dynamic>>.from(
              jsonData.map((doc) => Map<String, dynamic>.from(doc))
            );
            
            // 查找并移除匹配的文档
            final initialLength = documents.length;
            documents.removeWhere((doc) => doc['doc_id'] == docId);
            
            // 如果有文档被移除，更新分类文件
            if (documents.length < initialLength) {
              await entity.writeAsString(jsonEncode(documents));
              documentRemoved = true;
              print('FileServe: 从分类 ${path.basenameWithoutExtension(entity.path)} 中删除了文档');
            }
          } catch (e) {
            print('FileServe: 处理分类文件 ${entity.path} 失败: $e');
          }
        }
      }
      
      // 同时更新文档ID映射
      if (documentRemoved) {
        await removeDocIdMapping(docId);
      }
      
      return documentRemoved;
    } catch (e) {
      print('FileServe: 从分类中删除文档失败: $e');
      return false;
    }
  }

  /// 保存用户头像
  Future<bool> saveUserAvatar(List<int> imageBytes, String extension) async {
    try {
      if (!_initialized) await initialize();
      
      // 确保配置目录存在
      final configDir = Directory(path.join(_appDataDir, 'config'));
      if (!await configDir.exists()) {
        await configDir.create(recursive: true);
      }
      
      // 保存头像文件
      final avatarFile = File(path.join(configDir.path, 'user_pic.$extension'));
      await avatarFile.writeAsBytes(imageBytes);
      
      print('FileServe: 用户头像已保存: ${avatarFile.path}');
      return true;
    } catch (e) {
      print('FileServe: 保存用户头像失败: $e');
      return false;
    }
  }

  /// 获取用户头像路径
  Future<String?> getUserAvatarPath() async {
    try {
      if (!_initialized) await initialize();
      
      final configDir = Directory(path.join(_appDataDir, 'config'));
      if (!await configDir.exists()) {
        return null;
      }
      
      // 检查常见图片格式
      final extensions = ['jpg', 'jpeg', 'png', 'gif'];
      for (final ext in extensions) {
        final avatarFile = File(path.join(configDir.path, 'user_pic.$ext'));
        if (await avatarFile.exists()) {
          return avatarFile.path;
        }
      }
      
      return null;
    } catch (e) {
      print('FileServe: 获取用户头像路径失败: $e');
      return null;
    }
  }

  /// 删除用户头像
  Future<bool> deleteUserAvatar() async {
    try {
      if (!_initialized) await initialize();
      
      final configDir = Directory(path.join(_appDataDir, 'config'));
      if (!await configDir.exists()) {
        return false;
      }
      
      // 检查并删除所有可能的头像文件
      final extensions = ['jpg', 'jpeg', 'png', 'gif'];
      bool deleted = false;
      
      for (final ext in extensions) {
        final avatarFile = File(path.join(configDir.path, 'user_pic.$ext'));
        if (await avatarFile.exists()) {
          await avatarFile.delete();
          deleted = true;
        }
      }
      
      return deleted;
    } catch (e) {
      print('FileServe: 删除用户头像失败: $e');
      return false;
    }
  }

  Future<String?> getDocumentTitle(String documentId) async {
    try {
      if (!_initialized) await initialize();
      
      // 使用已有的方法获取文档路径
      final filePath = await getFilePathByDocId(documentId);
      if (filePath != null) {
        // 从路径中提取文件名
        final fileName = path.basename(filePath);
        return fileName;
      }
      
      // 如果找不到路径，使用文档ID作为后备选项
      return documentId;
    } catch (e) {
      print('获取文档标题失败: $e');
      return documentId;
    }
  }

  /// 根据文档名称获取文档ID
  /// 支持精确匹配和模糊匹配
  Future<String?> getDocumentIdByTitle(String title, {bool exactMatch = false}) async {
    try {
      if (!_initialized) await initialize();
      
      print('FileServe: 根据标题查找文档ID: $title (精确匹配: $exactMatch)');
      
      // 遍历所有分类文件，查找匹配的文档
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        print('FileServe: 缓存目录不存在');
        return null;
      }
      
      await for (final entity in cacheDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          try {
            final fileName = path.basename(entity.path);
            
            // 跳过标签文件，它们的结构不同
            if (fileName.endsWith('_tags.json') || fileName == 'tag.json') {
              continue;
            }
            
            final content = await entity.readAsString();
            final jsonData = jsonDecode(content);
            
            // 确保是文档列表格式
            if (jsonData is! List) {
              continue;
            }
            
            final List<dynamic> documents = jsonData;
            
            for (final doc in documents) {
              final docMap = Map<String, dynamic>.from(doc);
              final docTitle = docMap['title'] as String?;
              final docId = docMap['doc_id'] as String?;
              
              if (docTitle != null && docId != null) {
                if (exactMatch) {
                  // 精确匹配
                  if (docTitle == title) {
                    print('FileServe: 找到精确匹配的文档: $docTitle -> $docId');
                    return docId;
                  }
                } else {
                  // 模糊匹配（忽略大小写，包含关系）
                  if (docTitle.toLowerCase().contains(title.toLowerCase()) ||
                      title.toLowerCase().contains(docTitle.toLowerCase())) {
                    print('FileServe: 找到模糊匹配的文档: $docTitle -> $docId');
                    return docId;
                  }
                }
              }
            }
          } catch (e) {
            print('FileServe: 处理分类文件 ${entity.path} 失败: $e');
          }
        }
      }
      
      print('FileServe: 未找到匹配的文档: $title');
      return null;
    } catch (e) {
      print('FileServe: 根据标题获取文档ID失败: $e');
      return null;
    }
  }

  /// 获取所有文档的标题和ID映射
  Future<Map<String, String>> getAllDocumentTitleIdMappings() async {
    try {
      if (!_initialized) await initialize();
      
      print('FileServe: 获取所有文档的标题和ID映射');
      final Map<String, String> titleIdMap = {};
      
      // 遍历所有分类文件
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        print('FileServe: 缓存目录不存在');
        return titleIdMap;
      }
      
      await for (final entity in cacheDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          try {
            final fileName = path.basename(entity.path);
            
            // 跳过标签文件，它们的结构不同
            if (fileName.endsWith('_tags.json') || fileName == 'tag.json') {
              continue;
            }
            
            final content = await entity.readAsString();
            final jsonData = jsonDecode(content);
            
            // 确保是文档列表格式
            if (jsonData is! List) {
              continue;
            }
            
            final List<dynamic> documents = jsonData;
            
            for (final doc in documents) {
              final docMap = Map<String, dynamic>.from(doc);
              final docTitle = docMap['title'] as String?;
              final docId = docMap['doc_id'] as String?;
              
              if (docTitle != null && docId != null) {
                titleIdMap[docTitle] = docId;
              }
            }
          } catch (e) {
            print('FileServe: 处理分类文件 ${entity.path} 失败: $e');
          }
        }
      }
      
      print('FileServe: 获取到 ${titleIdMap.length} 个文档映射');
      return titleIdMap;
    } catch (e) {
      print('FileServe: 获取文档标题ID映射失败: $e');
      return {};
    }
  }

  /// 根据文档名称搜索相关文档（支持多个结果）
  Future<List<Map<String, String>>> searchDocumentsByTitle(String title) async {
    try {
      if (!_initialized) await initialize();
      
      print('FileServe: 搜索相关文档: $title');
      final List<Map<String, String>> results = [];
      
      // 遍历所有分类文件
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      if (!await cacheDir.exists()) {
        print('FileServe: 缓存目录不存在');
        return results;
      }
      
      await for (final entity in cacheDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          try {
            final fileName = path.basename(entity.path);
            
            // 跳过标签文件，它们的结构不同
            if (fileName.endsWith('_tags.json') || fileName == 'tag.json') {
              continue;
            }
            
            final content = await entity.readAsString();
            final jsonData = jsonDecode(content);
            
            // 确保是文档列表格式
            if (jsonData is! List) {
              continue;
            }
            
            final List<dynamic> documents = jsonData;
            final categoryName = path.basenameWithoutExtension(entity.path);
            
            for (final doc in documents) {
              final docMap = Map<String, dynamic>.from(doc);
              final docTitle = docMap['title'] as String?;
              final docId = docMap['doc_id'] as String?;
              
              if (docTitle != null && docId != null) {
                // 模糊匹配
                if (docTitle.toLowerCase().contains(title.toLowerCase()) ||
                    title.toLowerCase().contains(docTitle.toLowerCase())) {
                  results.add({
                    'title': docTitle,
                    'doc_id': docId,
                    'category': categoryName,
                  });
                }
              }
            }
          } catch (e) {
            print('FileServe: 处理分类文件 ${entity.path} 失败: $e');
          }
        }
      }
      
      print('FileServe: 找到 ${results.length} 个相关文档');
      return results;
    } catch (e) {
      print('FileServe: 搜索文档失败: $e');
      return [];
    }
  }

  /// ================== 分类标签管理方法 ==================

  /// 更新分类的标签统计
  Future<bool> updateCategoryTagStats(String category, List<String> tags) async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      final categoryTagFile = File(path.join(cacheDir.path, '${category}_tags.json'));
      
      Map<String, int> tagStats = {};
      
      // 读取现有标签统计
      if (await categoryTagFile.exists()) {
        final content = await categoryTagFile.readAsString();
        final jsonData = jsonDecode(content) as Map<String, dynamic>;
        
        for (final entry in jsonData.entries) {
          tagStats[entry.key] = entry.value as int;
        }
      }
      
      // 更新标签计数
      for (final tag in tags) {
        tagStats[tag] = (tagStats[tag] ?? 0) + 1;
      }
      
      // 保存更新后的标签统计
      await categoryTagFile.writeAsString(jsonEncode(tagStats));
      print('FileServe: 更新分类标签统计完成: $category');
      
      return true;
    } catch (e) {
      print('FileServe: 更新分类标签统计失败: $e');
      return false;
    }
  }

  /// 获取分类的热门标签（前N个）
  Future<List<Map<String, dynamic>>> getCategoryTopTags(String category, {int limit = 5}) async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      final categoryTagFile = File(path.join(cacheDir.path, '${category}_tags.json'));
      
      if (!await categoryTagFile.exists()) {
        print('FileServe: 分类标签文件不存在: $category');
        return [];
      }
      
      final content = await categoryTagFile.readAsString();
      final Map<String, dynamic> tagStats = jsonDecode(content);
      
      // 转换为列表并按计数排序
      final List<Map<String, dynamic>> sortedTags = [];
      for (final entry in tagStats.entries) {
        sortedTags.add({
          'tag': entry.key,
          'count': entry.value as int,
        });
      }
      
      // 按计数降序排序
      sortedTags.sort((a, b) => (b['count'] as int).compareTo(a['count'] as int));
      
      // 返回前N个标签
      return sortedTags.take(limit).toList();
      
    } catch (e) {
      print('FileServe: 获取分类热门标签失败: $e');
      return [];
    }
  }

  /// 获取分类的所有标签
  Future<List<Map<String, dynamic>>> getCategoryAllTags(String category) async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      final categoryTagFile = File(path.join(cacheDir.path, '${category}_tags.json'));
      
      if (!await categoryTagFile.exists()) {
        print('FileServe: 分类标签文件不存在: $category');
        return [];
      }
      
      final content = await categoryTagFile.readAsString();
      final Map<String, dynamic> tagStats = jsonDecode(content);
      
      // 转换为列表并按计数排序
      final List<Map<String, dynamic>> allTags = [];
      for (final entry in tagStats.entries) {
        allTags.add({
          'tag': entry.key,
          'count': entry.value as int,
        });
      }
      
      // 按计数降序排序
      allTags.sort((a, b) => (b['count'] as int).compareTo(a['count'] as int));
      
      return allTags;
      
    } catch (e) {
      print('FileServe: 获取分类所有标签失败: $e');
      return [];
    }
  }

  /// 根据标签获取分类下的相关文档
  Future<List<Map<String, dynamic>>> getDocumentsByTagInCategory(String category, String tag) async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      final categoryFile = File(path.join(cacheDir.path, '$category.json'));
      
      if (!await categoryFile.exists()) {
        print('FileServe: 分类文件不存在: $category');
        return [];
      }
      
      final content = await categoryFile.readAsString();
      final List<dynamic> documents = jsonDecode(content);
      
      final List<Map<String, dynamic>> matchedDocs = [];
      
      for (final doc in documents) {
        final docMap = Map<String, dynamic>.from(doc);
        final tags = docMap['tags'] as List<dynamic>?;
        
        if (tags != null && tags.contains(tag)) {
          matchedDocs.add(docMap);
        }
      }
      
      print('FileServe: 在分类 $category 中找到 ${matchedDocs.length} 个包含标签 "$tag" 的文档');
      return matchedDocs;
      
    } catch (e) {
      print('FileServe: 根据标签获取分类文档失败: $e');
      return [];
    }
  }

  /// 获取所有分类的标签概览
  Future<Map<String, List<Map<String, dynamic>>>> getAllCategoriesTagsSummary({int limitPerCategory = 3}) async {
    try {
      if (!_initialized) await initialize();
      
      final Map<String, List<Map<String, dynamic>>> summary = {};
      final categories = await getCategories();
      
      for (final category in categories) {
        final topTags = await getCategoryTopTags(category, limit: limitPerCategory);
        summary[category] = topTags;
      }
      
      print('FileServe: 获取所有分类标签概览完成，共 ${summary.length} 个分类');
      return summary;
      
    } catch (e) {
      print('FileServe: 获取所有分类标签概览失败: $e');
      return {};
    }
  }

  /// 清理空的分类标签文件
  Future<void> cleanEmptyCategoryTagFiles() async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      final categories = await getCategories();
      
      await for (final entity in cacheDir.list()) {
        if (entity is File && entity.path.endsWith('_tags.json')) {
          try {
            final content = await entity.readAsString();
            final Map<String, dynamic> tagStats = jsonDecode(content);
            
            if (tagStats.isEmpty) {
              await entity.delete();
              print('FileServe: 删除空的标签文件: ${entity.path}');
            }
          } catch (e) {
            print('FileServe: 处理标签文件 ${entity.path} 失败: $e');
          }
        }
      }
      
    } catch (e) {
      print('FileServe: 清理空标签文件失败: $e');
    }
  }

  /// ================== 全局标签管理方法 ==================

  /// 获取全局标签数据（tag.json）
  Future<Map<String, List<String>>> getGlobalTags() async {
    try {
      if (!_initialized) await initialize();
      
      final cacheDir = Directory(path.join(_appDataDir, 'cache'));
      final tagFile = File(path.join(cacheDir.path, 'tag.json'));
      
      if (!await tagFile.exists()) {
        print('FileServe: 全局标签文件不存在');
        return {};
      }

      final content = await tagFile.readAsString();
      final jsonData = jsonDecode(content) as Map<String, dynamic>;
      
      final Map<String, List<String>> tagData = {};
      for (final entry in jsonData.entries) {
        tagData[entry.key] = List<String>.from(entry.value as List);
      }
      
      print('FileServe: 获取全局标签数据完成，共 ${tagData.length} 个标签');
      return tagData;
      
    } catch (e) {
      print('FileServe: 获取全局标签数据失败: $e');
      return {};
    }
  }

  /// 获取所有标签名称列表
  Future<List<String>> getAllTagNames() async {
    try {
      final globalTags = await getGlobalTags();
      final tagNames = globalTags.keys.toList();
      tagNames.sort(); // 按字母顺序排序
      
      print('FileServe: 获取所有标签名称完成，共 ${tagNames.length} 个标签');
      return tagNames;
      
    } catch (e) {
      print('FileServe: 获取所有标签名称失败: $e');
      return [];
    }
  }

  /// 根据标签获取相关文档列表
  Future<List<String>> getDocumentsByTag(String tag) async {
    try {
      final globalTags = await getGlobalTags();
      final documents = globalTags[tag] ?? [];
      
      print('FileServe: 标签 "$tag" 关联 ${documents.length} 个文档');
      return documents;
      
    } catch (e) {
      print('FileServe: 获取标签相关文档失败: $e');
      return [];
    }
  }

  /// 获取标签统计信息（按文档数量排序）
  Future<List<Map<String, dynamic>>> getTagStatistics() async {
    try {
      final globalTags = await getGlobalTags();
      final List<Map<String, dynamic>> tagStats = [];
      
      for (final entry in globalTags.entries) {
        tagStats.add({
          'tag': entry.key,
          'documentCount': entry.value.length,
          'documents': entry.value,
        });
      }
      
      // 按文档数量降序排序
      tagStats.sort((a, b) => (b['documentCount'] as int).compareTo(a['documentCount'] as int));
      
      print('FileServe: 获取标签统计信息完成，共 ${tagStats.length} 个标签');
      return tagStats;
      
    } catch (e) {
      print('FileServe: 获取标签统计信息失败: $e');
      return [];
    }
  }

  /// 搜索标签（模糊匹配）
  Future<List<String>> searchTags(String query) async {
    try {
      final allTags = await getAllTagNames();
      final matchedTags = allTags
          .where((tag) => tag.toLowerCase().contains(query.toLowerCase()))
          .toList();
      
      print('FileServe: 搜索标签 "$query" 找到 ${matchedTags.length} 个匹配结果');
      return matchedTags;
      
    } catch (e) {
      print('FileServe: 搜索标签失败: $e');
      return [];
    }
  }

  /// 保存文档阅读位置
  Future<bool> saveDocumentReadingPosition(String docId, int currentPage, int totalPages) async {
    try {
      if (!_initialized) await initialize();
      
      final positionFile = File(path.join(_appDataDir, 'cache', 'reading_positions.json'));
      Map<String, dynamic> positions = {};
      
      // 读取现有位置数据
      if (await positionFile.exists()) {
        final content = await positionFile.readAsString();
        positions = jsonDecode(content);
      }
      
      // 更新或添加位置信息
      positions[docId] = {
        'current_page': currentPage,
        'total_pages': totalPages,
        'last_read_time': DateTime.now().toIso8601String(),
      };
      
      // 保存到文件
      await positionFile.writeAsString(jsonEncode(positions));
      print('FileServe: 保存文档阅读位置成功 - docId: $docId, page: $currentPage/$totalPages');
      return true;
    } catch (e) {
      print('FileServe: 保存文档阅读位置失败: $e');
      return false;
    }
  }

  /// 获取文档阅读位置
  Future<Map<String, dynamic>?> getDocumentReadingPosition(String docId) async {
    try {
      if (!_initialized) await initialize();
      
      final positionFile = File(path.join(_appDataDir, 'cache', 'reading_positions.json'));
      if (!await positionFile.exists()) {
        return null;
      }
      
      final content = await positionFile.readAsString();
      final Map<String, dynamic> positions = jsonDecode(content);
      
      if (positions.containsKey(docId)) {
        final position = positions[docId];
        print('FileServe: 获取文档阅读位置成功 - docId: $docId, page: ${position['current_page']}');
        return Map<String, dynamic>.from(position);
      }
      
      return null;
    } catch (e) {
      print('FileServe: 获取文档阅读位置失败: $e');
      return null;
    }
  }

  /// 删除文档阅读位置
  Future<bool> removeDocumentReadingPosition(String docId) async {
    try {
      if (!_initialized) await initialize();
      
      final positionFile = File(path.join(_appDataDir, 'cache', 'reading_positions.json'));
      if (!await positionFile.exists()) {
        return true;
      }
      
      final content = await positionFile.readAsString();
      final Map<String, dynamic> positions = jsonDecode(content);
      
      if (positions.containsKey(docId)) {
        positions.remove(docId);
        await positionFile.writeAsString(jsonEncode(positions));
        print('FileServe: 删除文档阅读位置成功 - docId: $docId');
      }
      
      return true;
    } catch (e) {
      print('FileServe: 删除文档阅读位置失败: $e');
      return false;
    }
  }

  /// 获取所有文档的阅读位置统计
  Future<Map<String, dynamic>> getReadingPositionStats() async {
    try {
      if (!_initialized) await initialize();
      
      final positionFile = File(path.join(_appDataDir, 'cache', 'reading_positions.json'));
      if (!await positionFile.exists()) {
        return {};
      }
      
      final content = await positionFile.readAsString();
      final Map<String, dynamic> positions = jsonDecode(content);
      
      // 计算统计信息
      final stats = <String, dynamic>{};
      for (final entry in positions.entries) {
        final docId = entry.key;
        final position = entry.value;
        final currentPage = position['current_page'] ?? 0;
        final totalPages = position['total_pages'] ?? 1;
        final progress = totalPages > 0 ? (currentPage / totalPages * 100).round() : 0;
        
        stats[docId] = {
          'current_page': currentPage,
          'total_pages': totalPages,
          'progress_percent': progress,
          'last_read_time': position['last_read_time'],
        };
      }
      
      return stats;
    } catch (e) {
      print('FileServe: 获取阅读位置统计失败: $e');
      return {};
    }
  }
}

class DifyConfig {
  Map<String, dynamic> config = {};
  
  Future<void> readConfig() async {
    final fileServe = FileServe();
    await fileServe.initialize();
    config = await fileServe.getConfig('Dify');
  }
  
  String returnConfigPath() {
    final fileServe = FileServe();
    return fileServe.returnConfigPath();
  }
} 